from NewsServer import app, cnx
from NewsServer.Classes.Article import Article
from NewsServer.Classes.ArticleSummary import ArticleSummary
from flask import abort, send_file, render_template, session, redirect, url_for, request
from Classes.forms import SignupForm, SigninForm
from flaskext.bcrypt import Bcrypt  # @UnresolvedImport


@app.route('/')
def home():
    cursor = cnx.cursor()
    cursor.callproc("get_article_summaries_range", (0,5))
    results = cursor.fetchall()
    cursor.close()
    
    SummaryList = []
    
    for row in results:
        SummaryList.append(ArticleSummary(*row))
       
    return render_template('home.html', SummaryList=SummaryList)

  
@app.route('/signup/', methods=['GET', 'POST'])
def signup():
    form = SignupForm()
    bcrypt = Bcrypt(app)
    if 'email' in session:
        return redirect(url_for('profile'))
    
     
    if request.method == 'POST':
        if form.validate() == False:
            return render_template('signup.html', form=form)
        else:
            password = bcrypt.generate_password_hash(form.password.data,10)
            #query = ('insert into users (username,firstname, lastname, email, pwdhash ) values (%s,%s, %s, %s, %s)')
            #cursor.execute(query, (form.username.data,form.firstname.data, form.lastname.data, form.email.data,password))
            cursor= cnx.cursor()
            cursor.callproc('create_new_user',[form.username.data,form.firstname.data, form.lastname.data, form.email.data,password])
            #cnx.commit()
            cursor.close()
        if request.method == 'POST':    
            session['email'] = form.email.data
            
            return redirect(url_for('profile')) 
     
    elif request.method == 'GET':
        return render_template('signup.html', form=form)


@app.route('/profile/')
def profile():

    if 'email' not in session:
        return redirect(url_for('signin'))

    else:
        cursor=cnx.cursor()
        cursor.callproc('check_email',[session['email']],)
        user_email=cursor.fetchall()
        cursor.close()
        username = user_email[0]
        for user in username:
            user = username[1]
            name = username[5] +" " + username[6]
            
            
            
        return render_template('profile.html',user=user, name = name)

@app.route('/signin/', methods=['GET', 'POST'])
def signin():
    form = SigninForm()
    if 'email' in session:
        return redirect(url_for('profile'))
    if request.method == 'POST':
        if form.validate() == False:
            return render_template('signin.html', form=form)
        else:
            session['email'] = form.email.data
            return redirect(url_for('profile'))
                                 
    elif request.method == 'GET':
        return render_template('signin.html', form=form)

@app.route('/signout/')
def signout():
    if 'email' not in session:
        return redirect(url_for('signin'))
    session.pop('email', None)
    return redirect(url_for('home'))


@app.route('/articles/<int:article_id>/')
def show_article(article_id):
    '''
    Get an article by the ID number, and display it to the page
    '''
    article = Article(article_id)
    if (article == None):
        abort(404)
    return render_template("article_display.html", article=article)


@app.route('/images/<path:filename>')
def serve_image(filename):
    if '..' in filename or filename.startswith('/'):
        abort(404)
    return send_file("images/" + filename)